import { computed, defineComponent, onMounted, reactive } from "vue";
import classes from "./index.module.scss"
import { useEmiter } from "@/hooks/useEmiter";
import { useTable } from "@/hooks/useTable";
import { WorkArea } from "@/components/WorkArea";
import Table, { GridType } from "@/components/Table";
import { ConditionItemType, ToolsItemType } from "@/hooks/useElementFormItem";
import { onEnterKeydown } from "@/hoc/onEnterDown";
import apiStore from "@/stores/apiStore";
import { useElMessageBox } from "@Tea/utils";
import { FN, UserListReturnType } from "@Tea/model";
import { httpCommonHandle } from "@/utils/httpUtils";

export default defineComponent({
  name: "userList",
  setup(props, ctx) {
    const { tableName } = useEmiter("userList")
    const { mountSearch, assginPaging, tableLoading, commonSearch, handleOneRow } = useTable(tableName)
    const { userPageList, putUserState, upgradeAuthority } = apiStore().api

    // 搜索条件
    const searchForm = reactive({
      username: "",
      enable: 1
    })
    // 禁用启用的标识
    const handleStateFlag = computed(() => {
      return searchForm.enable ? '停用' : '启用'
    })

    /**
     * @use 改变状态
     */
    const handleState = async () => {
      handleOneRow<UserListReturnType>((data) => {
        useElMessageBox({
          content: `确定要${handleStateFlag.value}吗？`,
          thenCallback: () => {
            httpCommonHandle({
              loading: tableLoading,
              callBack:() => putUserState({
                userId: data.userId,
                enable: searchForm.enable === 1 ? 0 : 1
              }),
              onSuccess: searchData
            })
          }
        })
      })
    }

    /**
     * @use 权限升级 
     */
    const upgrade = () => {
      handleOneRow<UserListReturnType>((data) => {
        useElMessageBox({
          content: `确定要将 ${data.username} 升级为管理员吗？`,
          thenCallback: () => {
            httpCommonHandle({
              loading: tableLoading,
              callBack:() => upgradeAuthority (data.userId),
              onSuccess: searchData
            })
          }
        })
      })
    }

    /**
     * @use 查询
     */
    const searchData = async () => {
      commonSearch(userPageList(assginPaging(searchForm)))
    }
    
    // 创建工具的配置
    const toolsList: ToolsItemType<typeof searchForm>[] = [
      {
        type: "button",
        content: "权限升级",
        disabled: computed(() => searchForm.enable === 0),
        attr: {
          onClick: upgrade
        }
      },
      {
        type: "button", content: handleStateFlag , attr: {
          onClick: handleState
        }
      },
      {
        type: "checkbox",
        optionLabel: computed(() => {
          return searchForm.enable ? '启用' :'停用'
        }),
        feild:"enable",
        attr: {
          'true-label': 1,
          'false-label': 0,
          onChange: () => searchData()
        },
        vModel: searchForm
      }
    ]

    // 创建搜索条件的配置
    const condition: ConditionItemType<typeof searchForm>[] = [
      {
        type: "text",
        vModel: searchForm,
        feild: "username",
        label: "用户名称",
        col: 4,
        attr: {
          placeholder: "用户名称",
          onClear: searchData,
          onKeydown:(e:KeyboardEvent) => onEnterKeydown(e, searchData)
        }
      },
    ]

    // agGrid 配置项
    const gridAttr: GridType = {
      columnDefs: [
        { headerName: "用户ID", checkboxSelection: true, field: "userId", width: 100 },
        { headerName: "用户名称", field: "username", width: 100 },
        { headerName: "用户账号", field: "account", width: 150 },
        { headerName: "用户头像", field: "avator", width: 100 },
      ],
      rowSelection: "single"
    }

    // 生命周期
    onMounted(() => {
      mountSearch(searchData)
      searchData()
    })

    return () => (
      <section class={`${classes.userList} m-padding m-fullBox m-window`}>
        <WorkArea
          tools={toolsList}
          condition={condition}
          onSearch={searchData}
        >
        </WorkArea>
        <Table
          v-loading={tableLoading.value}
          gridAttr={gridAttr}
          tableName={tableName}
        ></Table>
      </section>
    )
  },
})